﻿using System;
using System.Data;
using System.Linq;
using org.se.fs.presenter.ITask.Profile;
using org.se.fs.presenter.IView.Profile;
using org.se.fs.presenter.Library;

namespace org.se.fs.presenter.View.Profile
{
    public class InstitutionSubMenu : Template.SubMenu
    {
        private readonly IInstitutionSubMenu _view;
        private readonly IInstitution _task;
        private readonly IBranch _taskBranch;
        private DataTable _branch;

        public InstitutionSubMenu(IInstitutionSubMenu view) : this(view, new Task.Context.Institution(), new Task.Context.Branch()) { }

        public InstitutionSubMenu(IInstitutionSubMenu view, IInstitution task, IBranch taskBranch)
        {
            _view = view;
            _task = task;
            _taskBranch = taskBranch;
        }

        public override void Initialize()
        {
            _task.OnInsert += TaskOnInsert;
            _task.OnUpdate += TaskOnUpdate;
            _taskBranch.OnGetBranchActive += TaskBranchOnGetBranchActive;

            _view.SetLabel(Data.Rows.Count.Equals(0) ? @"Create New Institution" : @"Modify Institution");
            _view.ButtonAddVisible(Data.Rows.Count.Equals(0));
            _view.ButtonUpdateVisible(!Data.Rows.Count.Equals(0));

            if (!Data.Rows.Count.Equals(0))
                SetData();

            _taskBranch.GetBranchActive();
        }

        void TaskBranchOnGetBranchActive(object source, FormEvent e)
        {
            if(!e.IsSuccess)
                return;
            _branch = (DataTable) e.Value;
            var a = (_branch.AsEnumerable().Select(b => b.Field<string>("name"))).ToArray();
            _view.FillBranch(a);

            if (Data.Rows.Count.Equals(0))
                return;


            for(var i =0; i<_branch.Rows.Count;i++)
            {
                if (!_branch.Rows[i]["id"].ToString().Equals(Data.Rows[0]["branch_id"].ToString())) continue;
                _view.Index = i;
                break;
            }
        }

        protected override void TaskOnInsert(object source, FormEvent e)
        {
            _view.ButtonAddEnable(true);
            TriggerModify(new FormEvent(e.IsSuccess) { Exception = e.Exception, Value = e.Value });
        }

        protected override void TaskOnUpdate(object source, FormEvent e)
        {
            _view.ButtonUpdateEnable(true);
            TriggerModify(new FormEvent(e.IsSuccess) {Exception = e.Exception, Value = e.Value});
        }

        protected override void SetData()
        {
            if(Data.Rows.Count.Equals(0))
                return;

            _view.FullName = Data.Rows[0]["name"].ToString();
            _view.Code = Data.Rows[0]["code"].ToString();
            _view.Address = Data.Rows[0]["address"].ToString();
            _view.Fax = Data.Rows[0]["fax_num"].ToString();
            _view.Mobile = Data.Rows[0]["mobile_num"].ToString();
            _view.Tel = Data.Rows[0]["tel_num"].ToString();
            _view.ContactName = Data.Rows[0]["contact_name"].ToString();
            _view.ContactPosition = Data.Rows[0]["contact_position"].ToString();
            _view.ContactMobile = Data.Rows[0]["contact_mobile_num"].ToString();
            _view.ContactTel = Data.Rows[0]["contact_tel_num"].ToString();
        }

        public override void Add()
        {
            if (!Validate())
                return;

            _view.ButtonAddEnable(false);
            var a = Data.NewRow();

            a["name"] = _view.FullName ;
            a["code"] = _view.Code;
            a["address"]=_view.Address;
            a["fax_num"] = _view.Fax;
            a["mobile_num"] = _view.Mobile;
            a["tel_num"] = _view.Tel;
            a["contact_name"] = _view.ContactName;
            a["contact_position"]=_view.ContactPosition;
            a["contact_mobile_num"] = _view.ContactMobile;
            a["contact_tel_num"] = _view.ContactTel;
            a["branch_id"] = Convert.ToUInt64(_branch.Rows[_view.Index]["id"].ToString());
            a["branch_name"] = _branch.Rows[_view.Index]["name"].ToString();
            a["branch_code"] = _branch.Rows[_view.Index]["code"].ToString();
            a["user_create_id"] = Convert.ToUInt64(Config.User.Rows[0]["id"].ToString());
            Data.Rows.Add(a);
            _task.Insert(Data);
        }

        public override void Modify()
        {
            if(!Validate())
                return;

            _view.ButtonUpdateEnable(false);
            Data.Rows[0]["name"] = _view.FullName;
            Data.Rows[0]["code"] = _view.Code;
            Data.Rows[0]["address"] = _view.Address;
            Data.Rows[0]["fax_num"] = _view.Fax;
            Data.Rows[0]["mobile_num"] = _view.Mobile;
            Data.Rows[0]["tel_num"] = _view.Tel;
            Data.Rows[0]["contact_name"] = _view.ContactName;
            Data.Rows[0]["contact_position"] = _view.ContactPosition;
            Data.Rows[0]["contact_mobile_num"] = _view.ContactMobile;
            Data.Rows[0]["contact_tel_num"] = _view.ContactTel;
            Data.Rows[0]["branch_id"] = Convert.ToUInt64(_branch.Rows[_view.Index]["id"].ToString());
            Data.Rows[0]["branch_name"] = _branch.Rows[_view.Index]["name"].ToString();
            Data.Rows[0]["branch_code"] = _branch.Rows[_view.Index]["code"].ToString();
            Data.Rows[0]["user_create_id"] = Convert.ToUInt64(Config.User.Rows[0]["id"].ToString());
            _task.Update(Data);
        }

        protected override bool Validate()
        {
            if (string.IsNullOrEmpty(_view.FullName.Trim()))
            {
                TriggerValidate(new FormEvent(false) { Exception = new Exception("Invalid empty name.") });
                _view.FocusFullName();
                return false;
            }

            if (string.IsNullOrEmpty(_view.Code.Trim()))
            {
                TriggerValidate(new FormEvent(false) { Exception = new Exception("Invalid empty code.") });
                _view.FocusCode();
                return false;
            }

            if (_view.Index.Equals(-1))
            {
                TriggerValidate(new FormEvent(false) { Exception = new Exception("Invalid empty branch.") });
                _view.FocusBranch();
                return false;
            }

            TriggerValidate(new FormEvent(true));
            return true;
        }
    }
}
